package com.wcy.aop;

import com.wcy.annotation.aop.PreAuth;
import com.wcy.exception.UnAuthException;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

@Aspect
@Component
@Order(-1000)
public class AuthAspect {

    @Around(value = "@annotation(preAuth)")
    public Object preAuth(ProceedingJoinPoint joinPoint, PreAuth preAuth) throws Throwable{
//        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .currentRequestAttributes()).getRequest();
        String permsString = request.getHeader("X-Perms");

        boolean allowed = false;
        if(permsString != null){
//            System.out.println(permsString);
            String[] perms = permsString.split(",");
            for (String perm : perms) {
                if(perm.equals(preAuth.value())){
                    allowed = true;
                    break;
                }
            }
            if(!allowed&&preAuth.any().length>0){
                Set<String> reqPermSet = Arrays.stream(preAuth.any()).collect(Collectors.toSet());
                for (String perm : perms) {
                    if(reqPermSet.contains(perm)){
                        allowed = true;
                        break;
                    }
                }
            }
        }
        System.out.println("所需权限:"+preAuth.value());
        if(!allowed)
            throw new UnAuthException("权限验证未通过!");
        System.out.println("通过访问");
        return joinPoint.proceed();
    }
}
